package com.bpf.pubsub;

import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.Destination;
import javax.jms.JMSException;
import javax.jms.MessageProducer;
import javax.jms.Session;
import javax.jms.TextMessage;

import org.apache.activemq.ActiveMQConnectionFactory;

public class Publisher {

    private static final String TOPIC_NAME = "testTopic";
    private static final String USER = "admin";
    private static final String PASSWORD = "admin";
    private static final String BROKER_URL = "tcp://localhost:61616";
    private static final int SEND_SUM = 200;

    public static void main(String[] args) {
        ConnectionFactory connectionFactory = null;
        Connection connection = null;
        Session session = null;
        Destination destination = null;
        MessageProducer producer = null;

        try {
            connectionFactory = new ActiveMQConnectionFactory(Publisher.USER,Publisher.PASSWORD,Publisher.BROKER_URL);
            connection = connectionFactory.createConnection();
            connection.start();
            session = connection.createSession(true, Session.AUTO_ACKNOWLEDGE);
            destination = session.createTopic(Publisher.TOPIC_NAME);
            producer = session.createProducer(destination);
            sendMessage(session, producer);
            session.commit();
        }catch (Exception e){

        }finally {
            if(null != connection){
                try {
                    connection.close();
                } catch (JMSException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    public static void sendMessage(Session session, MessageProducer producer) throws JMSException {
        for (int i = 1; i <= Publisher.SEND_SUM; i ++){
            TextMessage message = session.createTextMessage("我的大美女"+i);
//            System.out.println("发布消息：" + i);
            producer.send(message);
        }
    }
}
